package com.sky.listener;

import com.sky.constant.MqConstant;
import com.sky.domain.DelayMessageProcessor;
import com.sky.domain.MultiDelayMessage;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Component
@Slf4j
public class Mqlistener {

    @Autowired
    private OrderMapper orderMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstant.DELAY_ORDER_QUEUE, durable = "true"),
            exchange = @Exchange(name = MqConstant.DELAY_EXCHANGE,delayed = "true"),
            key = MqConstant.DELAY_ORDER_ROUTING_KEY
    ))
    public void listenDelayMessage(MultiDelayMessage<Long> msg){
        log.info("接收到延迟消息：{}",msg);
        // 1. 根据ID查询订单状态
        Orders orders = orderMapper.getById(msg.getData());
        Integer payStatus = orders.getPayStatus();

        // 2. 检查订单状态
        if(payStatus.equals(Orders.PENDING_PAYMENT)&&!msg.hasNextDelay()){
            // 取消订单
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason("订单超时");
            orderMapper.update(orders);
        }else {
            try{
                rabbitTemplate.convertAndSend(MqConstant.DELAY_EXCHANGE,
                        MqConstant.DELAY_ORDER_ROUTING_KEY, msg,
                        new DelayMessageProcessor(msg.removeNextDelay().intValue()));
            }catch (Exception e){
                log.info("延迟消息发送异常！");
            }

        }

    }


}
